package br.com.rapidrest.chain;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;

import br.com.rapidrest.exception.ChainException;

public class Chain {

	private List<Command> commands;

	private ChainContext context;
	
	private int index = 0;

	public Chain(List<Command> commands) {
		super();
		this.commands = commands;
	}

	public void proceed() throws ChainException {
		try {
			if (index >= commands.size()) {
				context.getFilterChain().doFilter(context.getRequest(),
						context.getResponse());
			} else {
				Command nextCommand = commands.get(index++);
				nextCommand.execute(this);
			}
		} catch (IOException e) {
			throw new ChainException(e);
		} catch (ServletException e) {
			throw new ChainException(e);
		}
	}

	public List<Command> getCommands() {
		return commands;
	}

	public ChainContext getContext() {
		return context;
	}

	public void setContext(ChainContext context) {
		this.context = context;
	}

	public int getIndex() {
		return index;
	}

}